package com.lvbey.www;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

@Slf4j
@Getter
@Setter
public class ImageHandler {
    public String  lineSeparator = System.lineSeparator();

    public String image2ArtAscii(String imagePath, int maxLines) {

        try {
            return image2ArtAscii(new FileInputStream(new File(imagePath)), maxLines);
        } catch (FileNotFoundException e) {
            log.error("An error occurred while reading data from {}, details: "+String.valueOf(e),imagePath);
            return null;
        }
    }


    public String image2ArtAscii(InputStream in, int maxLines) {

        BufferedImage image = null;
        try {
            image = ImageIO.read(in);
        } catch (IOException e) {
            log.error("An error occurred while reading data from {}, details: "+String.valueOf(e));
            return null;
        }
        if(image == null){
            return null;
        }


        int width = image.getWidth();
        int height= image.getHeight();

        int newWidth=width;
        int newHeight = height;

        if(height > maxLines){

            newWidth = (int)Math.round(width * maxLines / height );
            newHeight = (int)Math.round(height * maxLines / height);
            log.debug("resize the original image {}x{} to new size {}x{}", width,height,newWidth,newHeight);
            image  = Tool.resize(image, newWidth, newHeight);
        }

        StringBuilder sb = new StringBuilder();
        for (int h = 0; h < newHeight; h++) {
            for (int w = 0; w < newWidth; w++) {
                int rgb = image.getRGB(w, h);
                sb.append(Tool.grayScale2Char(Tool.rgb2GrayScale(rgb), Constants.ASCII_CHARS));
            }
            sb.append(lineSeparator);
        }
        return sb.toString();
    }
}
